
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.LoopBack;
import protocol.meta.User;
import Utils.XoneUtil;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.netease.pkgRelated.XoneConsts;
import com.netease.pkgRelated.XoneConsts.MENU_ID;
import com.netease.util.PDEEngine;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityLogin;
import com.netease.xone.activity.ActivityX1Base;
import com.netease.xone.dataMgr.MemoryDataCenter;
import com.netease.xone.view.ProfileView;
import com.netease.xone.widget.CustomDialog.OnCustomDlgCancelListener;

import db.manager.ManagerAccount;
import db.manager.ManagerAccount.Account;

public class FragAccountMgr extends FragmentBase implements OnItemClickListener {

    private ListView mAccListView;
    private TextView mTvLogout;
    private TextView mTvAddAcc;
    private AccMgrAdapter mAdapter;
    private Cursor mCursor;
    private boolean mBEditState = false;
    private int mLoginTransId;
    private String mCurOpUserName = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        getActivity().setTitle(R.string.acc_manager);
        View view = inflater.inflate(R.layout.fragment_account_mgr, container, false);
        findViews(view);
        return view;
    }

    private void findViews(View view) {
        mAccListView = (ListView)view.findViewById(R.id.accmgr_list);
        mTvLogout = (TextView)view.findViewById(R.id.acc_logout);
        mTvAddAcc = (TextView)view.findViewById(R.id.acc_add);
        mTvLogout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                int  msgResId = R.string.acc_logout_anomyous_msg;
                if(mCursor !=null &&mCursor.getCount() >1 ) {
                    msgResId = R.string.acc_logout_dlg_msg;
                }                 
                
                new AlertDialog.Builder(getActivity()).setTitle(R.string.acc_logout_dlg_tip)
                        .setMessage(msgResId)
                        .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialoginterface, int j) {
                                String user = ManagerAccount.getInstance().getCurrentAccountId();
                                if (user != null) {
                                    ManagerAccount.getInstance().deleteAccountByUserId(user);
                                }
                                Account acc = ManagerAccount.getInstance().getNewestAccount();
                                if (acc != null) {
                                    doLogin(acc.mUserType, acc.mUserName, acc.mPassword,acc.mNickName);
                                } else {
                                    mLoginTransId = XoneService.getInstance().doAnomyousLogin();
                                }
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface diagloginterface, int i) {
                            }
                        }).show();

            }
        });
        mTvAddAcc.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityLogin.launch(getActivity(),true);
            }
        });
        mAccListView.setOnItemClickListener(this);
        mCursor = ManagerAccount.getInstance().getAllAccounts();
        mAdapter = new AccMgrAdapter(getActivity(), mCursor);
        mAccListView.setAdapter(mAdapter);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XoneService.getInstance().addListener(mXoneCallBack);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);
        if(mCursor != null){
            mCursor.close();
            mCursor = null;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        if (mBEditState) {
            com.actionbarsherlock.view.MenuItem item = menu.add(Menu.NONE, MENU_ID.menu_accmgr_done, 0,getString(R.string.done));
            item.setIcon(R.drawable.icon_action_done_selector);
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM );
        } else {
            com.actionbarsherlock.view.MenuItem item = menu.add(Menu.NONE, MENU_ID.menu_accmgr_edit, 0,getString(R.string.edit));
            item.setIcon(R.drawable.icon_action_delete_selector);
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM );
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        ActivityX1Base activity = (ActivityX1Base)getActivity();
        if (item.getItemId() == MENU_ID.menu_accmgr_edit) {
            mBEditState = true;
            activity.invalidateOptionsMenu();
        } else if (item.getItemId() == MENU_ID.menu_accmgr_done) {
            mBEditState = false;
            activity.invalidateOptionsMenu();
        }
          mAdapter.notifyDataSetChanged();
        
        return super.onOptionsItemSelected(item);
    }

    class AccMgrAdapter extends CursorAdapter {

        private Context mContext;
        private LayoutInflater mInflater;

        @SuppressWarnings("deprecation")
        public AccMgrAdapter(Context context, Cursor c) {
            super(context, c);
            mContext = context;
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        protected void onContentChanged() {
            super.onContentChanged();
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ViewHolder holder = (ViewHolder)view.getTag();
            if (null != holder) {
                String avatar = cursor.getString(ManagerAccount.COLUMNS_AVATAR);
                String nickName = cursor.getString(ManagerAccount.COLUMNS_NICKNAME);
                int loginType = cursor.getInt(ManagerAccount.COLUMNS_TYPE);
                int userAttr = cursor.getInt(ManagerAccount.COLUMNS_USER_ATTR);
                int isLast = cursor.getInt(ManagerAccount.COLUMNS_LOGIN);
                if (1 == isLast) {
                    holder.state.setBackgroundResource(R.drawable.checkbox_check);
                } else {
                    holder.state.setBackgroundResource(R.drawable.checkbox);
                }
                
//                if (!TextUtils.isEmpty(avatar)) {
//                    int size = getResources().getDimensionPixelSize(R.dimen.common_avatar_size);
//                    int roundSize = getResources().getDimensionPixelSize(R.dimen.common_avatar_rounder);
//                    holder.avatar.setServerClipSize(size, size);
//                    holder.avatar.setLoadingImage(avatar,ImageType.RoundMemCache,roundSize);
//                } else {
//                    holder.avatar.setImageDrawable(getResources().getDrawable(R.drawable.avatar_user_default_50));
//                }
                holder.avatar.setImageUrl(userAttr, avatar);
                holder.nickName.setText(nickName);
                String userId = cursor.getString(ManagerAccount.COLUMNS_USER_ID);
                holder.delete.setTag(userId);
                holder.delete.setClickable(true);
                holder.delete.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        final String user = (String)v.getTag();
                        if (null != user) {
                            String msg = null;
                            int msgResId = 0;
                            if(mCursor !=null &&mCursor.getCount() >1 ) {
                                String currId = ManagerAccount.getCurAccountId();
                                if(currId != null && currId.equals(user)){
                                    msgResId = R.string.acc_delete_dlg_msg;
                                } 
                            } else {
                                msgResId = R.string.acc_delete_anomyous_msg;
                            }
                            if(msgResId > 0){
                                msg = getString(msgResId);
                            } else {
                                msg = "";
                            } 
                            new AlertDialog.Builder(getActivity())
                                    .setTitle(R.string.acc_delete_dlg_tip)
                                    .setMessage(msg)
                                    .setPositiveButton(R.string.sure,
                                            new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(
                                                        DialogInterface dialoginterface, int j) {
                                                    ManagerAccount.getInstance()
                                                            .deleteAccountByUserId(user);
                                                    if (ManagerAccount.getInstance()
                                                            .getCurrentAccount() == null) {
                                                        Account acc = ManagerAccount.getInstance()
                                                                .getNewestAccount();
                                                        if (acc != null) {
                                                            doLogin(acc.mUserType, acc.mUserName,
                                                                    acc.mPassword,acc.mNickName);
                                                        } else {
                                                          mLoginTransId = XoneService.getInstance().doAnomyousLogin();
                                                        }
                                                    }
                                                }
                                            })
                                    .setNegativeButton(R.string.cancel,
                                            new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(
                                                        DialogInterface diagloginterface, int i) {
                                                }
                                            }).show();
                        }
                    }
                });
                holder.type.setText(XoneUtil.userTypeToString(getActivity(),loginType));
                if (mBEditState) {
                    holder.delete.setVisibility(view.VISIBLE);
                    holder.type.setVisibility(View.GONE);
                } else {
                    holder.delete.setVisibility(view.GONE);
                    holder.type.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = mInflater.inflate(R.layout.item_acc_mgr, parent, false);
            ViewHolder holder = new ViewHolder();
            holder.state = (ImageView)view.findViewById(R.id.accmgr_item_img);
            holder.avatar = (ProfileView)view.findViewById(R.id.profile_avatar);
            holder.type = (TextView)view.findViewById(R.id.accmgr_type_text);
            holder.nickName = (TextView)view.findViewById(R.id.accmgr_item_text);
            holder.delete = (TextView)view.findViewById(R.id.accmgr_item_button);
            view.setTag(holder);
            return view;
        }
    }

    class ViewHolder {
        ImageView state;
        ProfileView avatar;
        TextView nickName;
        TextView type;
        TextView delete;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        if (!mBEditState && null != mAdapter) {
            Cursor c = (Cursor)mAdapter.getItem(arg2);
            if (c != null) {
                int last = c.getInt(ManagerAccount.COLUMNS_LOGIN);
                boolean lastLogin = (last == 0 ? false : true);
                if (!lastLogin) {
                    String account = c.getString(ManagerAccount.COLUMNS_ACCOUNT);
                    String pwd = PDEEngine.PDecrypt(getActivity(),
                            c.getString(ManagerAccount.COLUMNS_PASSWORD));
                    int type = c.getInt(ManagerAccount.COLUMNS_TYPE);
                    String nickName = c.getString(ManagerAccount.COLUMNS_NICKNAME);
                    doLogin(type, account, pwd,nickName);
                }
            }
        }
    }

    private void doLogin(int type, String account, String pwd,String nickName) {
//        showWatting(getString(R.string.logining));
        String waitStr = getString(R.string.logining);
        if(!TextUtils.isEmpty(nickName)){
            waitStr = nickName + "\n"+ getString(R.string.logining);
        } 
        showCustomDialog(getActivity(), waitStr, mOnCustomDlgCancelListener);
        mLoginTransId = XoneService.getInstance().doLogin(type, account, pwd);
        mCurOpUserName = account;
    }
    
    private OnCustomDlgCancelListener mOnCustomDlgCancelListener = new OnCustomDlgCancelListener(){

        @Override
        public void onCancel() {
            XoneService.getInstance().cancelTransaction(mLoginTransId);
        }  
    };

    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLogin(int transactionId, User account) {
            if (mLoginTransId == transactionId){
//                stopWaiting();
                closeCustomDialog();
                LoopBack lb = new LoopBack();
                lb.mType = XoneConsts.LOOPBACK_TYPE.switch_account;
                lb.mData = new Boolean(true);
                XoneService.getInstance().doLoopBack(lb);
            }
            getActivity().finish();
        }

        @Override
        public void onLoginError(int transactionId, int errCode, String err) {
            if (mLoginTransId == transactionId) {
//                stopWaiting();
                closeCustomDialog();
                if (errCode != XoneServiceCode.LOGINREG_ERR_ACC_PW_ERROR
                        && errCode != XoneServiceCode.LOGINREG_ERR_EXTERNAL_VERIFY_ERROR
                        && errCode != XoneServiceCode.LOGINREG_ERR_USER_LOCKED) {
                    showToast(err);
                }
                if(errCode == XoneServiceCode.LOGINREG_ERR_ACC_PW_ERROR){
                    if(mCurOpUserName != null){
                        ManagerAccount.getInstance().deleteAccountByName(mCurOpUserName);
                        MemoryDataCenter.getInstance().put(XoneConsts.MEMORY_ACC_DELETE_TAG, new Boolean(true));
                    }
                }
            }
        }
    };
}
